Vue 幫我們制定許多常用的 directive 如:v-if, v-show, v-for.. 功能強大,也好奇是怎麼做到的呢?讓我們一起動手來設計自己的 directive 吧!

import Vue 並使用 directive 來設計,
| 參數一 | 參數二 | 
|---|---|
| directive name | 物件,event hook | 
import Vue from 'vue';
Vue.directive('directiveName', {
  // event hook
});
使用的時候 name 前面要加上前綴:v-
如果使用大 / 小駝峰命名方式轉成用
連接號連接。
<div v-directive-name></div>
這樣就完成建立與使用 directive 囉!
Vue.directive('focus', {
  // 當绑定元素插入到 DOM 中。
  inserted: function (el) {
    // 聚焦元素
    el.focus();
  }
})
範例中可以看到物件內有 inserted 字串,這是 directive hook 之一,
inserted 代表,當绑定元素插入到 DOM 的時候,可以說 directive 啟動第一次要做什麼事情。
範例中 inserted 函式 el 參數指的是 directive 所绑定的元素,可以用来直接操作 DOM
如果綁在
input上面el就會是 input
因此 directive 啟動的時候會自動 focus 所綁定的 DOM。
<input v-focus>
| hook | 作用 | 
|---|---|
| bind | directive 第一次绑定到元素時調用,初始化動作(一次)。 | 
| inserted | 被绑定元素插入父節點時調用。 | 
| update | directive 傳入的參數,更新的時後會調用。 | 
| componentUpdated | 參數更新完成時調用。 | 
| unbind | 指令與元素解除時調用。 | 
| hook | 作用 | 
|---|---|
| el | directive 所绑定的元素,可以用来直接操作 DOM 。 | 
| binding | bind 的對象(傳的值或 function) | 
| vnode | 虛擬節點。 | 
| oldVnode | 上一個虛擬節點。 | 
除了 el 之外,其他參數都應該是只讀的,盡量不要修改他們。
貼到 main.js 上 try try。
Vue.directive('test', {
    bind: function (el, binding, vnode) {
    var s = JSON.stringify;
    el.innerHTML =
      'name: '       + s(binding.name) + '<br>' +
      'value type: ' + typeof binding.value + '<br>' +
      'value: '      + binding.value + '<br>' +
      'expression: ' + s(binding.expression) + '<br>' +
      'argument: '   + s(binding.arg) + '<br>' +
      'modifiers: '  + s(binding.modifiers) + '<br>' +
      'vnode keys: ' + Object.keys(vnode).join(', ');
  }
});
<div v-test:ironman.2017="vue"></div>

注意
binding.value是否因傳入function導致JSON.stringif後變成undefined文章上 example 有調整過囉。
設計 directive 會綁在 password input 上面,
並帶入 checkbox 雙向綁定的 value
因此 bind 與 update 都會觸發
function togglePassword (val) {
  return val ? 'text' : 'password';
}
// custom toggle password
Vue.directive('toggle-password', {
  bind (el, binding) {
    el.type = togglePassword( binding.value );
  },
  update (el, binding) {
    el.type = togglePassword( binding.value );
  }
});
<template>
<!-- 
  2. 在 password input 上面使用 v-toggle-password 帶入 checkbox 的 value
-->
<input
  v-model="password"
  v-toggle-password="togglePassword"
  @keyup.enter="login"
  type="password"
  id="inputPassword"
  class="form-control"
  placeholder="Password" required />
<!-- 1. check box 雙向綁定[布林] -->
<div class="squaredFour" style="margin: 20px 10px;">
  <input
    type="checkbox"
    v-model="togglePassword"
    id="togglePassword" />
  <label for="togglePassword" class="checkbox-icon"></label>
  <label for="togglePassword">顯示密碼</label>
</div>
</template>
<script>
export default {
  data () {
    return {
      togglePassword: false,
    }
  },
}
</script>
實作小範例入門 Vue & Vuex 2.0 - github 完整範例
使用 git checkout 切換每天範例。
有個問題 v-test:ironman.2017="vue"
這裡面的 vue 要用單引號包起來, 即
v-test:ironman.2017="'vue'"
否則value type 和 value 都說 undefine
.